package com.group11.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group11.common.pojo.Enterprise;
import com.group11.common.pojo.ResponseResult;
import com.group11.common.vo.EnterpriseVo;
import com.group11.job.domain.Job;
import com.group11.job.domain.JobFavor;
import com.group11.job.mapper.JobFavorMapper;
import com.group11.job.mapper.JobMapper;
import com.group11.job.service.JobService;
import com.group11.job.service.UserService;
import com.group11.job.vo.JobVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    @Autowired
    private JobFavorMapper jobFavorMapper;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private UserService userService;

    @Override
    public boolean favorJob(int userid, int jobid) {

        QueryWrapper<JobFavor> eq = new QueryWrapper<JobFavor>()
                .eq("user_id", userid)
                .eq("job_id", jobid);
        JobFavor jobFavor1 = jobFavorMapper.selectOne(eq);
        if (jobFavor1 != null) {
            jobFavorMapper.delete(eq);
        } else {
            JobFavor jobFavor = new JobFavor();
            jobFavor.setUserId(userid);
            jobFavor.setJobId(jobid);
            jobFavor.setFavorTime(LocalDateTime.now().toString());
            jobFavorMapper.insert(jobFavor);
        }
        return true;
    }

    @Override
    public JobVo getJob(int jobid) {
        QueryWrapper<Job> eq = new QueryWrapper<Job>()
                .eq("id", jobid)
                .eq("is_deleted", "0");
        Job job = jobMapper.selectOne(eq);
        if (job == null) {
            return null;
        }

        ResponseResult<EnterpriseVo> enterpriseById = userService.getEnterpriseById(job.getEntId());
        if (enterpriseById.getCode() != 200 || enterpriseById.getData() == null) {
            return null;
        }

        return new JobVo(job, enterpriseById.getData());
    }

    @Override
    public List<JobVo> getJobs() {
        QueryWrapper<Job> eq = new QueryWrapper<Job>().eq("is_deleted", "0");
        List<Job> jobs = jobMapper.selectList(eq);
        ArrayList<JobVo> jobVos = new ArrayList<>();
        jobs.forEach(job -> {
            ResponseResult<EnterpriseVo> enterpriseById = userService.getEnterpriseById(job.getEntId());
            if (enterpriseById.getCode() == 200 && enterpriseById.getData() != null) {
                jobVos.add(new JobVo(job, enterpriseById.getData()));
            }
        });
        return jobVos;
    }
}
